package com.example.shiyan4;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnBindService, btnUnbindService, btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind = false;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 将返回的IBinder对象转换为MyServiceBinder
            serviceBinder = (MyService.MyServiceBinder) service;
            if (serviceBinder != null) {
                isServiceBind = true; // 确保绑定成功后更新状态
                Log.d("MainActivity", "Service bound successfully");
            } else {
                Log.e("MainActivity", "Failed to bind service");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 当服务断开连接时，清空serviceBinder并重置绑定状态
            serviceBinder = null;
            isServiceBind = false;
            Log.d("MainActivity", "Service disconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBindService = findViewById(R.id.btnBindService);
        btnUnbindService = findViewById(R.id.btnUnbindService);
        btnGetStatus = findViewById(R.id.btnGetStatus);
        tvServiceStatus = findViewById(R.id.tvServiceStatus);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, MyService.class);
        if (v.getId() == R.id.btnBindService) {
            // 如果service尚未绑定就绑定，如果已经绑定则忽略
            if (!isServiceBind) {
                bindService(intent, conn, BIND_AUTO_CREATE);
                isServiceBind = true; // 确保绑定请求后更新状态
            }
        }
        if (v.getId() == R.id.btnUnbindService) {
            // 如果service已经绑定，则可以解绑，否则忽略
            if (isServiceBind) {
                unbindService(conn);
                isServiceBind = false; // 确保解绑后更新状态
            }
        }
        if (v.getId() == R.id.btnGetStatus) {
            // 如果service已经绑定，获取service的count计数并显示在界面上
                tvServiceStatus.setText("Service Count:" + MyService.count);
            } else {
//                tvServiceStatus.setText("Service Not Bind");
            }
        }
    }
